package com.example.demo.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import liquibase.integration.spring.SpringLiquibase;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Order(1)
@Configuration
public class DruidConfig {
    @Value(value = "${spring.datasource.url}")
    private String url;
    @Value(value = "${spring.datasource.username}")
    private String username;
    @Value(value = "${spring.datasource.password}")
    private String password;

    @Bean
    public DataSource getDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(url);
        dataSource.setUsername(username);// 用户名
        dataSource.setPassword(password);// 密码
        return dataSource;
    }

    @Bean
    public ServletRegistrationBean staViewServlet(){
        ServletRegistrationBean bean
                =new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
        Map<String,String> initParams= new HashMap<>();

        initParams.put("loginUserName","admin");
        initParams.put("loginPassword","123456");
        // 默认就是允许所有访问ip
        initParams.put("allow","");
        // 拒绝访问的ip
        initParams.put("deny","");
        bean.setInitParameters(initParams);
        return bean;
    }


    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean bean
                =new FilterRegistrationBean(new WebStatFilter());
        Map<String,String> initParams=new HashMap<>();
        // filter不拦截的请求
        initParams.put("exclusions","*.js,*.css,/druid/*");
        bean.setInitParameters(initParams);
        // filter拦截的请求
        bean.setUrlPatterns(Arrays.asList("/*"));
        return bean;
    }

}
